package com.lizx.framework.web.smart.framework.core.utils;

import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 反射工具
 * @Author: lizx
 * @Description:
 * @Date: Create in 2019/1/17 5:01 PM
 */
public class SmartReflectionUtil {
    private static final Logger LOGGER = Logger.getLogger(SmartReflectionUtil.class);

    /**
     * 初始化实例
     * @param cls
     * @return
     */
    public static Object newInstance(Class<?> cls){
        Object instance = null;
        try {
            instance = cls.newInstance();
        } catch (Exception e) {
            LOGGER.error(cls+"初始化实例失败");
            throw new RuntimeException(e);
        }
        return instance;
    }

    /**
     * 调用方法
     * @param object
     * @param method
     * @param args
     * @return
     */
    public static Object invokeMethod(Object object, Method method, Object... args){
        Object result = null;
        try {
            method.setAccessible(true);
            result = method.invoke(object, args);
        } catch (Exception e) {
            LOGGER.error(method+"调用方法失败");
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 设置成员变量
     * @param obj
     * @param field
     * @param value
     */
    public static void setField(Object obj, Field field, Object value){
        try {
            field.setAccessible(true);
            field.set(obj,value);
        }catch (Exception e){
            LOGGER.error(field+"设置成员变量失败");
            throw new RuntimeException(e);
        }
    }
}
